﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeckoPhotos.Models;
using GeckoPhotos.Repository;

namespace GeckoPhotos.Service
{
    public class UserServiceLayer
    {
        private readonly IUserRepository _repository;

        public UserServiceLayer(IUserRepository repository)
        {
            if (repository == null)
                throw new ArgumentNullException();

            _repository = repository;
        }

        public User GetByUsernameAndPassword(string username, string password)
        {
            return _repository.Where(u => u.Username == username && u.Password == password).FirstOrDefault();
        }

        public User CreateUser(string username, string password, string displayName, string email)
        {
            User user = new User
            {
                Username = username,
                Password = password,
                DisplayName = displayName,
                Email = email,
            };

            Message message = new Message
            {
                DateTime = DateTime.UtcNow,
                InstigatorUser = user,
                MessageTypeID = (int)MessageTypeEnum.UserCreated,
                Text = Properties.Resources.MessageUserCreated,
            };

            user.Messages.Add(message);

            _repository.Insert(user);
            return user;
        }

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            var user = GetByUsernameAndPassword(username, oldPassword);
            if (user == null)
                return false;

            user.Password = newPassword;

            _repository.Update(user);

            return true;
        }

        public IEnumerable<User> GetUsers()
        {
            var result = _repository.All();
            if (result == null)
                throw new InvalidOperationException();
            return result;
        }

        public User GetById(int userId)
        {
            return _repository.Where(u => u.UserID == userId).FirstOrDefault();
        }

        public void UpdateUser(int userId, string newUsername, string optionalNewPassword, string newDisplayName, string newEmail)
        {
            User user = GetById(userId);
            if (user == null)
                throw new ArgumentException("UserID not found in database.");

            user.Username = newUsername;
            if (!string.IsNullOrEmpty(optionalNewPassword))
                user.Password = optionalNewPassword;
            user.DisplayName = newDisplayName;
            user.Email = newEmail;

            _repository.Update(user);
        }
    }
}
